var timer = null;
$(function () {
	
		var Datagrid = {};
		//选择节点
		$('#comboxNode').combobox({
			url: "/api/kettleSlaveServers/search/findByName" + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    method:'get',
			editable: false,
		    loadFilter: function(data){
		    	var datas = data.content;
				var allCheck = {'id':'','name':'全部'};
				datas.unshift(allCheck);
		    	return datas;
		    }
		});
		//选择运行情况
		$('#comboxRunning').combobox({
			//url: '',
			valueField: 'id',
		    textField: 'name',
		   // method:'get',
			editable: false,
		    /*loadFilter: function(data){
				var allCheck = {'id':'','name':'全部'};
        		data.content.unshift(allCheck);
		    	return data.content;
		    }*/
			data:[{id:'',name:'全部',selected:'true'},{id:'true',name:'运行中'},{id:'false',name:'停止中'}]
		});
		
		$("#datagrid").datagrid({
			url : BASE_URL_KETTLE_SLAVE_SERVER_SEARCH + '/findByName?v=' + Math.random(),
			method:'get',
			autoRowHeight:true,
			nowrap:false,
			singleSelect:true,
			striped:true,
			pageSize:20,
			rownumbers:true,
			pageList:[20],
			columns:[[
						{field:'name',title:'节点名称',width:100,align:'left'},
						{field:'ipaddr',title:'IP地址',width:100},
						{field:'port',title:'类型',width:100, formatter: function(value, rowData, rowIndex){
								return value == true?"主服务器":"从服务器";
							}
						},
						{field:'remark',title:'是否运行',width:100},
						{field:'wqe',title:'操作',width:130,align:'center',
							formatter: function(value,row,index){
							var url = BASE_URL_KETTLE_SLAVE_SERVER_CRUD + '/' + row.id;
							if(row.type=="Kettle"){
								return '<a href="javascript:void(0);"  data-url="' + url + '" class="default_btn fl showMon">运行监控</a><a href="javascript:void(0);" class="default_btn fl showLog">运行日志</a><a href="javascript:void(0);" class="default_btn fl showSta" data-id="' + row.id + '">运行统计</a>';	
							}else{
								return '<a href="javascript:void(0);" class="default_btn fl showMon" style="visibility:hidden">运行监控</a><a href="javascript:void(0);" data-url="' + url + '" class="default_btn fl showMon">运行监控</a><a href="javascript:void(0);" class="default_btn fl showMon" style="visibility:hidden">运行监控</a>';	
							}
							}
						}
					]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			loadFilter:function(data){//alert(data.page.length)
				return {
					total:data.totalElements,
					rows: data.content
				};
			},
			//条件查询
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;	
				param.sort = 'createTime,desc';
				var name = $('#comboxNode').combobox('getText');
				if(name !="全部"){
					param.name = name;
				}				
				var ifRunning = $('#comboxRunning').combobox('getText');				
				if(ifRunning !="全部"){
					param.ifRunning = ifRunning;
				}
				$(".datagrid-header-rownumber").text("序号");
				
				//alert(param.size)
			}
			
		});			
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		});
		
		function mon_data(target){
			var row = $('#datagrid').datagrid('getSelected');
			var url;
			$(target + " .mon_name").text(row.name);
			$(target + " .mon_type").text(row.isMaster?"主服务器":"从服务器");
			$(target + " .mon_hostName").text(row.ipaddr);
			logId = row.id;
			if(row.type == "Kettle")
			{
				var dataParam = {
						ipaddr : row.ipaddr,
						port : row.port
				};
				ServiceInformationDisplay2(dataParam); 
			}else{
				var dataParam = {
						ipaddr : row.ipaddr,
						port : row.port
				};
				ServiceInformationDisplay2(dataParam);
			};
            $('#showMonWin').window('open');
            
		}
		//运行监控
		$("body").delegate(".showMon","click",function(e) {
			mon_data("#showMonWin");
        });	
		//运行监控显示
		$('#showMonWin').window({
			width:980,
			height:470,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			onBeforeClose:function(){ 
				if(timer)
				{
					clearInterval(timer);
					timer = null;
				}
			   $('#datagrid').datagrid('clearSelections');
		   }
		});
		
		$('#showMonWin').window('close');  //关闭窗口
			
		/*function showMon(url)
		{							
				$.ajax({
					url:url,
					type:'get',
					dataType:'json',
					contentType:"application/json",
					success:function(data){
						//alert(Stringify);
						var connectUrl = "http://"+data.hostName+":8082/myHandler";
						ServiceInformationDisplay(connectUrl); 
					}
				});
		};*/

			function ServiceInformationDisplay(url){
				var sock = SockJsCreator(url);
				sock.onopen = function() {
					 sock.send('test');
				 };
				 sock.onmessage = function(e) {
					 var Data = JSON.parse(e.data); 
					 if(!chart || !chart.series)
						{
						 return;
						}
					 var series = chart.series[0];
					 if(!chart1 || !chart1.series)
						{
						 return;
						}
					 var series1 = chart1.series[0];
					 var x = (new Date()).getTime(),
					 y = Math.random();
					 series.addPoint([x, Data.cpu.totalPerc], true, true);
					 series1.addPoint([x,Data.memory.used],true,true);
				 };
				 sock.onclose = function() {
					  
				 }; 
				Highcharts.setOptions({
					global: {
						useUTC: false
					}
				});
				
				//cpu使用率曲线图
				var chart;
				chart = new Highcharts.Chart({
					chart: {
						renderTo: 'container',
						type: 'spline',
						animation: Highcharts.svg,
						// don't animate in old IE               
						marginRight: 10,
						events: {
							load: function() {}
						}
					},
					title: {
						text: 'CPU',
						x: 0 //center
					},
					subtitle: {
					   /* text: '平均值：5.6%',
						x: 0*/
					},
					credits: {
						enabled: false
					},
					xAxis: {
						type: 'datetime',
						tickPixelInterval: 150
					},
					yAxis: [{
						title: {
							text: '使用率 (%)'
						},
						plotLines: [{
							value: 0,
							width: 1,
							color: '#808080'
						}]
					}],
					tooltip: {
						formatter: function() {
							return '<b>' + this.series.name + '</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2);
						}
					},
					legend: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: 'CPU使用率',
						data: (function() { // generate an array of random data                             
							var data = [],
							time = (new Date()).getTime(),
							i;
							for (i = -19; i <= 0; i++) {
								data.push({
									x: time + i * 1000,
									y: 1
								});
							}
							return data;						
						})()
					}]
				}); 
			
			
			  //内存使用率曲线图
				var chart1;
				chart1 = new Highcharts.Chart({
					chart: {
						renderTo: 'chart2',
						type: 'spline',
						animation: Highcharts.svg,
						// don't animate in old IE               
						marginRight: 10,
						events: {
							load: function() {}
						}
					},
					title: {
						text: '物理内存',
						x: 0 //center
					},
					subtitle: {
						/*text: '平均值：2201.11(MB)',
						x: 0*/
					},
					credits: {
						enabled: false
					},
					xAxis: {
						type: 'datetime',
						tickPixelInterval: 150
					},
					yAxis: [{
						title: {
							text: '使用内存 (MB)'
						},
						plotLines: [{
							value: 0,
							width: 1,
							color: '#808080'
						}]
					}],
					tooltip: {
						formatter: function() {
								return '<b>使用内存：</b>'+
								this.y + 'MB';
							
						}
					},
					legend: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: 'Random data',
						data: (function() { // generate an array of random data                             
							var data = [],
							time = (new Date()).getTime(),
							i;
							for (i = -19; i <= 0; i++) {
								data.push({
									x: time + i * 1000,
									y: 1024
								});
							}
							return data;
						})()
					}]
				});
			}
		
		
		
		
		
		//运行日志
		var logId = "";
		$("body").delegate(".showLog","click",function(e) {
			//mon_data("#showLogWin");
			var row = $('#datagrid').datagrid('getSelected');
			var url;
			$("#showLogWin .mon_name").text(row.name);
			$("#showLogWin .mon_type").text(row.isMaster?"主服务器":"从服务器");
			$("#showLogWin .mon_hostName").text(row.ipaddr);
			logId = row.id;
			$("#logTable").datagrid({
				url : BASE_URL_SLAVE_SERVER_LOGS_SEARCH + '/findByExample' + '?v=' + Math.random(),
				method:'get',
				autoRowHeight:true,
				nowrap:false,
				singleSelect:true,
				rownumbers:true,
				striped:true,
				scrollbarSize:0,
				selectOnCheck:false,
				onClickRow: function (rowIndex, rowData) {
							$(this).datagrid('unselectRow', rowIndex);
						},
				columns:[[
							{field:'createTime',title:'记录时间',width:20},
							{field:'contents',title:'日志内容',width:80}
						]],
				onLoadSuccess:function(data){
					$("#logTable").parent().addClass("text_left");
				},
				loadFilter:function(data){
					return {
								total: data.totalElements,
								rows: data.content
							}
				},
				//条件查询
				onBeforeLoad:function(param){
					$(".datagrid-header-rownumber").text("序号");
					param.page -= 1;
					param.size = param.rows;
					delete param.rows;
					param.sort = 'createTime,desc';
					param.id = logId;
					
				}
			});
            $('#showLogWin').window('open');
        });
		//运行日志显示
		$('#showLogWin').window({
			width:980,
			height:470,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			onBeforeClose:function(){ 
			   $('#datagrid').datagrid('clearSelections');
		   }
		});
		
		$('#showLogWin').window('close');  //关闭窗口
		
		
		
		
		//运行统计
		$("body").delegate(".showSta","click",function(e) {
			$('#showStaWin').window('open');
			$('#chart4, #chart3').css("width","927px");
			var nodeId = $(this).data("id");
			showSta(nodeId);
			$("#tabs").tabs("select",0);
            
			
        });
		//运行统计显示
		$('#showStaWin').window({
			width:980,
			height:470,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			resizable:false,
			resizable:false,
			onBeforeClose:function(){ 
			   $('#datagrid').datagrid('clearSelections');
		   }
		});
		$('#showStaWin').window('close');  //关闭窗口
		
		function showSta(nodeId)
		{
			
			if(!nodeId)
			{
				return;
			}
			setNodeInfo(null);
			if($('#chart3').highcharts())
			{
				$('#chart3').highcharts().destroy();
			}
			
			getNodeInfo(nodeId);
			getTwelveHourAgoTime(nodeId);
			function getNodeInfo(nodeId) {
				if(!nodeId)
				{
					return;
				}
				$.ajax({
					url:BASE_URL_SLAVE_SERVER_STATISTICS_SEARCH +"/countByNodeIdAndTime?nodeId=" + nodeId + "&v=" + Date.parse(new Date()),
					type:'get',
					contentType:"application/json",
					success:function(data){	
						if(data && data.content)
						{
							setNodeInfo(data.content[0]);
						}
					},
					error: function() {
						$.messager.alert('错误','<p>服务异常，查询节点信息失败，请稍后重试!</p>','error');
					}
				});
			}

			function setNodeInfo(nodeInfo) {
				
				if(nodeInfo)
				{
					$(".mon_name").html(nodeInfo.name);
					$(".mon_hostName").html(nodeInfo.hostName);
					/*$(".mon_port").html(nodeInfo.port);*/
					$(".mon_type").html(nodeInfo.isMaster? "主服务器":"从服务器");
					$(".mon_allRunTimes").html(nodeInfo.allRunTimes);
					$(".mon_errorRate").html(nodeInfo.errorRate.replace("%", ""));
					$(".mon_mostRunTimes").html(nodeInfo.mostRunTimes);
					
					var errorRate = parseFloat($(".mon_errorRate").html());
					var correctRate = 100 - errorRate;
					var errorChartData = [{
							name:'错误率',
							y:errorRate,
							color: '#fe8080'
						},
						{
							name:'正常率',
							y:correctRate,
							color:'#ffc65c'
						}];
					if($('#chart4').highcharts())
					{
						$('#chart4').highcharts().destroy();
					}
					drawErrorRateChart(errorChartData);
				}
				else
				{
					$(".mon_name").html("");
					$(".mon_hostName").html("");
					/*$(".mon_port").html("");*/
					$(".mon_type").html("");
					$(".mon_allRunTimes").html("");
					$(".mon_errorRate").html("");
					$(".mon_mostRunTimes").html("");
					
					if($('#chart4').highcharts())
					{
						$('#chart4').highcharts().destroy();
					}
				}
			}
			
			function getTwelveHourAgoTime(nodeId) {
				if(!nodeId)
				{
					return;
				}
				$.ajax({
					url:BASE_URL_SLAVE_SERVER_STATISTICS_SEARCH +"/findTwelveHourAgoTime?nodeId=" + nodeId + "&v=" + Date.parse(new Date()),
					type:'get',
					contentType:"application/json",
					success:function(data){	
						if(data && data.content)
						{
							var chartData = {categories:[], data:[]};
							for(var i = 0; i < data.content.length; ++i)
							{
								chartData.categories.push(data.content[i].runEndTime.split(" ")[1]);
								chartData.data.push({
									y:+data.content[i].runTime
								});
							}
							if($('#chart3').highcharts())
							{
								$('#chart3').highcharts().destroy();
							}
							drawElapsedTimeChart(chartData);
						}
					},
					error: function() {
						$.messager.alert('错误','<p>服务异常，查询节点信息失败，请稍后重试!</p>','error');
					}
				});
			}
			
			function drawElapsedTimeChart(data) {
				var average = 0;
				var sum = 0;
				var len = data.data.length;
				for(var i = 0; i　< len; ++i)
				{
					sum += +data.data[i].y;
				}
				if(len > 0)
				{
					average = Math.round(sum/len);
				}
				
				$('#chart3').highcharts({
					chart: {
						type: 'spline'
					},
					title: {
						text: '平均耗时',
						x: 0 //center
					},
					subtitle: {
						text: '平均值：' + average + '(分钟)',
						x: 0
					},
					credits: {
						enabled: false
					},
					legend: {
						enabled: false
					},
					xAxis: {
						type:"datetime",
						categories: data.categories,
						//maxZoom: 14 * 24 * 3600000, // fourteen days
						title: {
							text: null
						},			
						gridLineWidth:1,
						gridLineDashStyle:'Dash'
					},
					yAxis: {
						title: {
							text: '耗时(分钟)'
						},
						min: 0,
						gridLineDashStyle:'Dash'
					},
					tooltip: {
						formatter: function() {
								return '<b>耗时：</b>'+
								this.y + '分钟';
						}
						
					},
					
					series: [{
						name: '',
						data: data.data
					}]
				});
			}
			
			function drawErrorRateChart(data) {
			
				$('#chart4').highcharts({
					chart: {
						plotBackgroundColor: null,
						plotBorderWidth: null,
						plotShadow: false
					},
					title: {
						text: '错误率'
					},
					tooltip: {
						pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
					},
					credits: {
						enabled: false
					},
					legend: {
						enabled: true,
						align: 'right',
						verticalAlign: 'top',
						layout: 'vertical',
						floating: true,
						itemStyle: {
							fontWeight: 'normal'
						},
						labelFormat: '<p">{name}</p>'
						/*labelFormatter: function(){
							var textColor = this.name == "按时"? '#fe8080':'#32d6c5';
							return '<p style="color:' + textColor + ';">' + this.name + '</p>';
						}*/
					},
					plotOptions: {
						pie: {
							allowPointSelect: false,
							cursor: 'pointer',
							dataLabels: {
								enabled: true,
								color: '#000000',
								connectorColor: '#000000',
								format: '<b>{point.name}</b>: {point.percentage:.2f} %'
							}
						}
					},
					series: [{
						showInLegend: true,
						type: 'pie',
						name: '节点运行情况',
						data: data
					}]
				});
			}
		}
		
		
});

function ServiceInformationDisplay2(dataParam){
	if(timer!=null){
		clearInterval(timer);
	}
	timer = setInterval(function(){NodeInformationDisplay(dataParam);},1000);
	function NodeInformationDisplay(dataParam){
		$.ajax({
			url:BASE_URL_NODE_CLUSTER +'/runningInformations',
			type:"get",
			data:dataParam,
			dataType:"json",
			contentType:"application/json",
			success:function(result){
			var series = chart.series[0];	//cpu使用率曲线图
			var series1 = chart1.series[0];	//内存使用率曲线图
				var x = (new Date()).getTime(),   //时间轴    
				y = Math.random();			
				
				if(result.node){
					//将数据显示出来		
					series.addPoint([x, result.cpu], true, true);
					series1.addPoint([x,result.memory],true,true);
				}else{
					series.addPoint([x, 0], true, true);
					series1.addPoint([x,0],true,true);
				}
			}
		});
		
	}
	
	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	
//cpu使用率曲线图
	var chart;
	chart = new Highcharts.Chart({
		chart: {
			renderTo: 'container',
			type: 'spline',
			animation: Highcharts.svg,
			// don't animate in old IE               
			marginRight: 10,
			events: {
				load: function() {}
			}
		},
		title: {
			text: 'CPU',
			x: 0 //center
		},
		subtitle: {
			/* text: '平均值：5.6%',
            x: 0*/
		},
		credits: {
			enabled: false
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: [{
			title: {
				text: '使用率 (%)'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		}],
		tooltip: {
			formatter: function() {
				return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2);
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: 'CPU使用率',
			data: (function() { // generate an array of random data                             
				var data = [],
				time = (new Date()).getTime(),
				i;
				for (i = -19; i <= 0; i++) {
					data.push({
						x: time + i * 1000,
						y: 0
					});
				}
				return data;
			})()
		}]
	}); 
	
//内存空闲曲线图
	var chart1;
	chart1 = new Highcharts.Chart({
		chart: {
			renderTo: 'chart2',
			type: 'spline',
			animation: Highcharts.svg,
			// don't animate in old IE               
			marginRight: 10,
			events: {
				load: function() {}
			}
		},
		title: {
			text: '物理内存',
			x: 0 //center
		},
		subtitle: {
			/*text: '平均值：2201.11(MB)',
	        x: 0*/
		},
		credits: {
			enabled: false
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: [{
			title: {
				text: '使用内存 (MB)'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		}],
		tooltip: {
			formatter: function() {
				return '<b>使用内存：</b>'+
				this.y + 'MB';	        	
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: 'Random data',
			data: (function() { // generate an array of random data                             
				var data = [],
				time = (new Date()).getTime(),
				i;
				for (i = -19; i <= 0; i++) {
					data.push({
						x: time + i * 1000,
						y: 0
					});
				}
				return data;
			})()
		}]
	});
	
}

//查询
function onSearch(){
	$("#datagrid").datagrid("reload", BASE_URL_KETTLE_SLAVE_SERVER_SEARCH + '/findByName?v=' + Math.random());	
	

}